package com.java.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: wjr
 * @Description:
 * @Date Created in  2020-09-03 0:15
 * @Modified By:
 */
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器开始执行");
        //对所有servlet请求设置编码集
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("utf-8");
        String requestURI = request.getRequestURI();
        String val = (String) request.getSession().getAttribute("val");
        //对某些资源放行
        if (requestURI.endsWith("/") || requestURI.endsWith("msg.jsp")
        || requestURI.endsWith("/index.jsp")||requestURI.endsWith("/login")
        || val!=null){
            filterChain.doFilter(servletRequest,servletResponse);//读取下一个servlet或者filter
        }else{
            response.sendRedirect("msg.jsp");
        }
    }

    @Override
    public void destroy() {

    }
}
